package com.wanwen.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanwen.dto.ModuleDto;
import com.wanwen.entity.Modules;
import com.wanwen.entity.RoleModules;
import com.wanwen.entity.RoleUsers;
import com.wanwen.mapper.ModuleMapper;
import com.wanwen.mapper.ModuleRoleMapper;
import com.wanwen.mapper.RoleUserMapper;
import com.wanwen.utils.CommonUtil;
import com.wanwen.utils.UITreeFactory;

@RestController
@RequestMapping("/userRoleModuleController")
public class UserRoleModuleController {
	@Autowired
	private ModuleMapper moduleMapper;
	@Autowired
	private RoleUserMapper roleUserMapper;
	@Autowired
	private ModuleRoleMapper moduleRoleMapper;

	/**
	 * 查询当前角色所拥有的模块并渲染一个树
	 * 
	 * @param userId 用户Id
	 * @return
	 */
	@RequestMapping("/getModuleByUser")
	public Object getModuleByUser(String userId) {
		// 构建查询用户角色的wrapper并添加用户Id条件
		QueryWrapper<RoleUsers> roleUserWrapper = new QueryWrapper<RoleUsers>().eq("users_id", userId);
		// 根据用户Id查询用户角色表
		List<RoleUsers> userRoles = roleUserMapper.selectList(roleUserWrapper);
		if (userRoles.size() != 0) {
			List<Integer> roleIds = new ArrayList<Integer>();// 初始化集合用来存储用户角色表查询出的角色Id
			for (RoleUsers item : userRoles) {// 存储角色Id
				roleIds.add(item.getRoleId());
			}
			// 所有的已转的模块业务对象
			List<ModuleDto> mdtoList = new ArrayList<ModuleDto>();
			// 根据角色id查询角色模块表
			List<RoleModules> roleModules = moduleRoleMapper
					.selectList(new QueryWrapper<RoleModules>().in("role_id", roleIds));
			if (roleModules.size() == 0) {
				UITreeFactory.loadTree(mdtoList);
				return UITreeFactory.moduleTreeList;
			} else {
				// 初始化集合用来存储角色模块表查询出的模块Id
				List<Integer> modulIds = new ArrayList<Integer>();
				// 存储角色Id
				for (RoleModules item : roleModules) {
					modulIds.add(item.getModulId());
				}
				// 根据模块id查询模块表
				List<Modules> moduleByRole = moduleMapper
						.selectList(new QueryWrapper<Modules>().in("id", modulIds).orderByAsc("weight"));
				for (Modules mod : moduleByRole) {
					mdtoList.add(CommonUtil.getModuleDtoByModule(mod));
				}
				UITreeFactory.loadTree(mdtoList);
				return UITreeFactory.moduleTreeList;
			}
		} else {
			return null;
		}

	}

}
